#include "NcCompute.h"
#include "NcWrapper.h"

namespace OCPP
{
	using namespace Volume;
	void NcCompute::extract(int levelIndex, int timeIndex,const VolumeOptions& options)
	{
		std::map<String,std::shared_ptr<NcWrapper> > ncNcWrapperList;
		std::vector<std::tuple<String, NcOutputList> > ncOutputListList;

		for (const auto& [fileName, varName] : _computeList)
		{
			if (ncNcWrapperList[fileName] == nullptr)
			{
				ncNcWrapperList[fileName] = std::make_shared<NcWrapper>();
				if (!ncNcWrapperList[fileName]->open(fileName)) 
				{
					OCPP_LOG_ERROR << fileName << " can't open.\n";
					return;
				}
			}
			auto& ncWrapper = ncNcWrapperList[fileName];
			auto data = ncWrapper->read(varName, levelIndex, timeIndex, options);
			ncOutputListList.push_back({fileName, data });
		}
		
		if (ncOutputListList.size() == 0)
		{
			return;
		}

		auto& [fileName, data] = ncOutputListList[0];

		size_t comp = data.size();

		for (size_t i = 0; i < comp; i++)
		{
			NcGridDataList dataListCompute;
			for (auto& ncOuputList : ncOutputListList)
			{
				auto& [fileName, data] = ncOuputList;
				NcOutput& gridData = data[i];
				gridData._vecFloat = ncNcWrapperList[fileName]->readFloat(data[i]);
				ncNcWrapperList[fileName]->fixByAttr(gridData, options);
				gridData.ClipIf(options);
				dataListCompute.emplace_back(std::move(gridData));
			}

			VolumeGridData ncGridData = _algorithm->onCompute(dataListCompute, options);
			if (ncGridData.isValid())
			{
				options.getWriter().write(ncGridData, options);
			}
		}
	}
}


